import React from 'react';
import { connect } from 'dva';

import { Modal, Form, Input,InputNumber } from 'antd';

import { Upload, Button } from 'antd';

//import jrQrcode from 'jr-qrcode';


const FormItem = Form.Item;

/*
const loadImg = (src) => {
    const paths = Array.isArray(src) ? src : [src];
    const promise = [];
    paths.forEach((path) => {
        promise.push(new Promise((resolve, reject) => {
            let img = new Image();
            img.crossOrigin = "Anonymous";
            img.src = path;
            img.onload = () => {
                resolve(img);
            };
            img.onerror = (err) => {
                console.log('图片加载失败')
            }
        }))
    });
    return Promise.all(promise);

}

const getImageData = async (url, src, x, y, w) => {
    const imgsrc = jrQrcode.getQrBase64(url)
    const [img1, img2] =  await loadImg([imgsrc, src])

    let canvas = document.createElement('canvas')

    const width = img2.width
    const height = img2.height

    const [x2,y2,w2 ] = [
      Math.round( width * x / 100 ),
      Math.round(height * y / 100 ),
      Math.round( width * w / 100 )
    ]

    canvas.width = width*2
    canvas.height = height*2
    let ctx = canvas.getContext("2d")

        ctx.drawImage(img2, 0, 0, width*2, height*2)
        ctx.drawImage(img1, x2*2, y2*2, w2*2, w2*2)
        ctx.save()
        let imageURL = canvas.toDataURL("image/png")

    return imageURL

}
*/

@connect(({ partnerOrgModel }) => ({ partnerOrgModel }))
class FormCreate extends React.Component {
  state = {
    image: null
  }
  componentDidMount(){
    // 获取多对一字段的下拉列表框选项所需要的数据
  }

  handleCancel(){
    const { dispatch } = this.props;
    dispatch({
      type: 'partnerOrgModel/hide',
      payload: 'newForm'
    });
  }

  handleOk(){
    const { form: { validateFields } } = this.props;
    const { dispatch } = this.props;
    validateFields( async  (err, values) => {
      if (!err) {
        const { image } = this.state
        const vals = {...values, image }

        const {x,y,w} = vals
        delete vals.x
        delete vals.y
        delete vals.w

        if( image ){
          //const newImage = await getImageData('hello world',
          //    image, x,y,w )


          vals.image = unescape(image.split(',')[1])
          console.log( vals.image )
        }
        else{
          delete vals.image
        }

        vals.ref = JSON.stringify({
          x,y,w
        });

        vals.is_company = true


        await dispatch({
          type: 'partnerOrgModel/create',
          payload : { vals},
        });

        dispatch({
          type: 'partnerOrgModel/hide',
          payload: 'newForm'
        });

      }
    });
  }

    getBase64 = (info) => {
        const img = info.file.originFileObj
        const reader = new FileReader();
        reader.addEventListener('load', async (reader) => {

          const newImage =  reader.target.result
          this.setState({image: newImage })

        });
        reader.readAsDataURL(img);
    }



  render() {
    const { partnerOrgModel:{ visible }, form: { getFieldDecorator }  } = this.props;

    const image = this.state.image

    return (
      <div>
        <Modal title='新增'
          visible={visible.newForm}
          onOk={()=>this.handleOk()}
          onCancel={()=>this.handleCancel()}
        >
          <Form>
            <FormItem label="name">
              {getFieldDecorator('name', {
                /*  rules: [{ required: true }], */
                initialValue: 'n',
              })(
                <Input />
              )}
            </FormItem>
            <FormItem label="email">
              {getFieldDecorator('email', {
                /*  rules: [{ required: true }], */
                initialValue: 'n@email',
              })(
                <Input />
              )}
            </FormItem>
            <FormItem label="二维码左边相对原图左边的位置 %">
              {getFieldDecorator('x', {
                /*  rules: [{ required: true }], */
                initialValue: 59,
              })(
                <InputNumber />
              )}
            </FormItem>
            <FormItem label="二维码上边相对原图上边的位置 %">
              {getFieldDecorator('y', {
                /*  rules: [{ required: true }], */
                initialValue: 84,
              })(
                <InputNumber />
              )}
            </FormItem>
            <FormItem label="二维码边长相对于原图宽度的比例 %">
              {getFieldDecorator('w', {
                /*  rules: [{ required: true }], */
                initialValue:  25,
              })(
                <InputNumber />
              )}
            </FormItem>
            <FormItem label="图片">
              {getFieldDecorator('image', {
                /*  rules: [{ required: true }], */
               // initialValue: 'n@email',
              })(

                <div>
                        <Upload fileList={[]}
                            name="avatar"
                            onChange={this.getBase64}
                        >
                            <Button icon="upload">上传图片
                            </Button>


                        </Upload>
                    <img alt= '选择图片'
                      style={{width: '20%',height:'20%' }}
                      src={image}
                      id='mix_img'
                    />

                </div>
              )}
            </FormItem>
          </Form>
        </Modal>

      </div>
    );
  }
}

export default Form.create()(FormCreate);

